<template>
  <view>
	  <!-- 公共组件-每个页面必须引入 -->
	  <public-module></public-module>
    <view class="dialog-quotation">
		<div style="background: #fff;padding:0 32rpx">
			<u--form labelPosition="left" :model="form" :rules="rules" ref="form" labelWidth="100" errorType="toast">
				<u-form-item label="品类"  borderBottom @click="showChooseDP" prop="categoryName" required>
					<u--input fontSize="14" inputAlign="right" :value="form.categoryName" disabled disabledColor="none" placeholder="请选择品类" border="none" style="pointer-events: none"></u--input>
					<div slot="right" class="form-icon">
						<u-icon slot="right" name="arrow-right" ></u-icon>
					</div>
				</u-form-item>
				<u-form-item label="厂家牌号"  required borderBottom @click="showGoods" ref="item1"  prop="goodsSn">
					<u--input fontSize="14" inputAlign="right" :value="form.brandName+form.goodsSn" disabled disabledColor="none" placeholder="请选择厂家牌号" border="none" style="pointer-events: none"></u--input>
					<div slot="right" class="form-icon">
						<u-icon slot="right" name="arrow-right" ></u-icon>
					</div>
				</u-form-item>
				
				<u-form-item  label="所在地" borderBottom prop="sendArea" required>
					<uni-data-picker v-slot:default placeholder="请选择所在地" popup-title="请选择所在地" :localdata="dataTree"
					  :modelValue="form.sendAreaId"
					  :map="{text:'areaName',value:'areaId'}" @change="onchange" @popupopened="onpopupopened"
					  @popupclosed="onpopupclosed" :clear-icon="false" style="width:100%">
					  <view class="form-row ">
					    <view class="input" style="display: block;" v-if="form.sendArea != ''"> {{form.sendArea}}</view>
					    <view v-else><text style="color:#c0c4cc">请选择所在地</text></view>
					    <u-icon slot="right" name="arrow-right" ></u-icon>
					  </view>
					</uni-data-picker>
				</u-form-item>
				<u-form-item  label="价格电议"  borderBottom >
					<div style="display: flex;justify-content: flex-end;">
						<u-switch v-model="form.goodsPrice" activeValue="电议" :inactiveValue="null"></u-switch>
					</div>
				</u-form-item>
				<u-form-item  label="价格" prop="goodsPrice" borderBottom required>
					<u--input  fontSize="14"  inputAlign="right" v-model="form.goodsPrice" border="none"  placeholder="请输入价格" :disabled="form.goodsPrice=='电议'"></u--input>
				</u-form-item>
				<u-form-item  label="库存数量(吨)" prop="goodsStock" borderBottom required>
					<u--input  fontSize="14"  inputAlign="right" v-model="form.goodsStock" border="none"  placeholder="请输入库存数量"></u--input>
				</u-form-item>
				<u-form-item label="发货时间(天)"  borderBottom prop="sendWaitDays" required>
					<u--input  fontSize="14"  inputAlign="right" v-model="form.sendWaitDays" border="none"  placeholder="请输入发货时间"></u--input>
			
				</u-form-item>
				
				<u-form-item  label="包装(吨/包)" prop="goodsWeight" borderBottom required>
					<u--input  fontSize="14"  inputAlign="right" v-model="form.goodsWeight" border="none"  placeholder="请输入包装数量"></u--input>
				</u-form-item>
				
				<u-form-item  label="起订量(吨)" prop="minBuyNum" borderBottom required>
					<u--input  fontSize="14"  inputAlign="right" v-model="form.minBuyNum" border="none"  placeholder="请按包装的倍数输入"></u--input>
				</u-form-item>
				
				<u-form-item label="产品图片"  borderBottom  labelPosition="top" prop="goodsImages" required> 
				  <div style="margin-top:20rpx;" >
					  <u-upload url="https://upload.qiniup.com" :fileList="form.goodsImages" @afterRead="handleAfterRead($event,'goodsImages')" 
					  :previewFullImage="true"
					   @delete="deleteImg($event,'goodsImages')"
						name="3"  :maxCount="5" style="width:200rpx;height:200rpx;">
					  </u-upload>
			      </div>
				</u-form-item>
				<!-- <u-form-item label="物性表"  borderBottom  labelPosition="top">
				  <div style="margin-top:20rpx" >
					  <u-upload url="https://upload.qiniup.com" :fileList="form.properties" @afterRead="handleAfterRead($event,'properties')"  accept="all"
					   @delete="deleteImg($event,'properties')"
						name="3"  :maxCount="5" style="width:200rpx;height:200rpx;">
						<div style="display: flex;flex-direction: column;align-items: center;justify-content: center;width: 80px;height: 80px;background-color: #f4f5f7;border-radius: 2px;margin: 0 8px 8px 0;sbox-sizing: border-box;">
							<u-icon name="file-text-fill" size="28" color="#D3D4D6"></u-icon>
						</div>
					  </u-upload>
				  </div>
				</u-form-item>			
				<u-form-item label="质检报告"  :borderBottom="false"  labelPosition="top">
				  <div style="margin-top:20rpx" >
					  <u-upload url="https://upload.qiniup.com" :fileList="form.report" @afterRead="handleAfterRead($event,'report')"  accept="all"
					   @delete="deleteImg($event,'report')"
						name="3"  :maxCount="5" style="width:200rpx;height:200rpx;">
						<div style="display: flex;flex-direction: column;align-items: center;justify-content: center;width: 80px;height: 80px;background-color: #f4f5f7;border-radius: 2px;margin: 0 8px 8px 0;sbox-sizing: border-box;">
							<u-icon name="file-text-fill" size="28" color="#D3D4D6"></u-icon>
						</div>
					  </u-upload>
				  </div>
				</u-form-item>	 -->	
			</u--form>
		</div>
    </view>
	<view class="change-button" style="z-index: 3;">
	  <u-button text="提交" color="linear-gradient(180deg, #FF5E01 0%, #FF5E01 100%)"  @click="saveForm" :loading="btnLoading"></u-button> <!--:disabled="!includeProduct"-->
	</view>

		

	 
	 <!--牌号厂家-->
	 <goodsSn ref="goodsSn" @chooseItem="chooseGoodsSn"></goodsSn>
	 
	 <!-- 品名 -->
	 <u-picker :show="showCategory" :columns="columns" keyName="name" @confirm='chooseCategory'
	   @cancel='showCategory = false'></u-picker>
    
  </view>
</template>

<script>
	const defaultForm={
		     goodsId:'',
	  	     categoryId: "",//品名id
	  	     categoryName:'',
	  	     brandId: "",//厂家id
	  	     brandName: "",//厂家名
	  	     goodsSn: "",//牌号
	  	     sendArea: "",//地址
	  	     sendAreaId: "",//地址区id
	  	     goodsStock: "",//库存
	  	     goodsPrice: "",//价格
	  	     goodsWeight: undefined,//包装
	  	     sendWaitDays: '',//发货日期
	  	     goodsImages:[],//图片
			 minBuyNum:'',//起订量
			 properties:[],
			 report:[]
	      };
 import {getAreaList,getGoodsCate,goodsDetail} from '@/config/api.js'
 import {setGoods} from '@/config/api2.js'
 import goodsSn from '@/components/module/goodsSn';
 import store from '@/store';
 import {
   imgCheck
 } from '@/plugins/upload/upload.js'
  export default {
	  components: {
	    goodsSn
	  },
    data() {
    	return {
    	   form:JSON.parse(JSON.stringify(defaultForm)),
    	   btnLoading:false,
    	   dataTree: [],
    	   showTime:false,
    	   value1: Number(new Date()),
    	   title:'新增商品',
    	   type:'',
    	   rules:{
    	   	categoryName: [{
    	   			required: true,
    	   			message: '请选择品类',
    	   			// 可以单个或者同时写两个触发验证方式
    	   			trigger: ['blur', 'change']
    	   		}],
    	   	goodsSn: [{
    	   			required: true,
    	   			message: '请选择厂家牌号',
    	   			// 可以单个或者同时写两个触发验证方式
    	   			trigger: ['blur', 'change']
    	   		}],
    		sendWaitDays: [{
    				required: true,
					type:'integer',
    				message: '发货时间请输入整数',
    				// 可以单个或者同时写两个触发验证方式
    				trigger: ['blur', 'change']
    			}],
    		sendArea: [{
    				required: true,
    				message: '请选择所在地',
    				// 可以单个或者同时写两个触发验证方式
    				trigger: [ 'change']
    			}],
			 goodsPrice: [{
					required: true,
					message: '请输入价格',
					// 可以单个或者同时写两个触发验证方式
					trigger: ['blur', 'change'],
					
				}],
			goodsStock: [{
					required: true,
					message: '请输入库存数量',
					// 可以单个或者同时写两个触发验证方式
					trigger: ['blur', 'change'],
					type:'number'
				}],
			goodsWeight: [{
					required: true,
					message: '请输入包装数量',
					type:'number',
					// 可以单个或者同时写两个触发验证方式
					trigger: ['blur', 'change']
				}],
			minBuyNum: [{
					required: true,
					message: '请按包装的倍数输入起订量',
					// 可以单个或者同时写两个触发验证方式
					trigger: ['blur', 'change'],
					type:'number',
					validator: (rule, value, callback) => {
						// 上面有说，返回true表示校验通过，返回false表示不通过
						// uni.$u.test.mobile()就是返回true或者false的
						let value1 = value  ? parseFloat(value) : 0
						if(value1 == 0){
							return false
						}else{
							let step = (parseInt((this.form.minBuyNum*1e5).toFixed(0))) % (parseInt((this.form.goodsWeight*1e5).toFixed(0)))
							if(step!=0){
								return false
							}else{
								return true
							}	
						}
					},
				}],
				goodsImages:[{
					required: true,
					message: '请上传产品图片',
					// 可以单个或者同时写两个触发验证方式
					trigger: ['change'],
					type:'array'
				}]
    	   },

		  goodsId:'',
		  fileList1: [],
		  showCategory:false,
		  columns:[]
    	}
    },
    onLoad(e) {
	  this.form = JSON.parse(JSON.stringify(defaultForm));
	  this.type = e.type;
	  if(this.type == 'edit'){
		  this.goodsId = e.goodsId
	  }
	  this.init()
	  // #ifdef MP
	  this.$refs.form.setRules(this.rules)
	  // #endif
    },
    
    filters:{
    	
		
    },
    methods: {
		//选择品名
		chooseCategory(e){
			this.form.categoryId = e.value[0].id;
			this.form.categoryName = e.value[0].name;
			this.form.brandId = '';
			this.form.brandName = '';
			this.form.goodsSn = '';
			this.showCategory = false
		
		},
		showChooseDP(){
			this.showCategory = true
		},
		//获取主营品类
		getClassList(){
			getGoodsCate().then((res)=>{
				let list = [];
				res.forEach((el)=>{
					el.list.forEach((ee)=>{
						list.push({name:el.categoryName+'/'+ee.categoryName,id:ee.categoryId})
					})
				})
				this.columns = [list]
			})
		},
		showGoods(){
			uni.pageScrollTo({
			   scrollTop: 0,
			   duration: 0,
			})
			this.$refs.goodsSn.init(this.form.categoryId,'addGoodss');
		},
		
		chooseGoodsSn(e){
			this.form.brandId = e.brandId;
			this.form.brandName = e.brandName;
			this.form.goodsSn = e.goodsSn;
		},
		
		//删除图片
		deleteImg(event,key){
			this.form[key].splice(event.index,1)
		},
		
		handleAfterRead(event,key) {
			console.log("event",event)
			if(event.file.size>2*1024*1000){
				uni.showToast({
					title:'图片大小超过2M，请重新选择照片',
					icon:'none'
				})		
				return
			}
			
			let fileType = event.file.url.substring(event.file.url.lastIndexOf('.'));
			
		     // #ifdef H5
			  console.log("------------------")
			   fileType =event.file.name.substring(event.file.name.lastIndexOf('.')); 
			 // #endif
			 
			if(fileType !== '.jpg' && fileType !== '.jpeg' && fileType !== '.png' && fileType !== '.pdf'){
				uni.showToast({
				  title: '请上传jpg、jpge或png的图片或pdf文件！',
				  icon: 'none',
				  duration: 2000,
				});
			  return false;
			}
			uni.showLoading({
				title: '上传中',
			});
			imgCheck(event.file.url).then((res)=>{
				if(res != ''){
					this.form[key].push({url:res})		
				}
				uni.hideLoading()
			}).catch(()=>{
				uni.hideLoading()
			})
		},
		
    	init(){
    		if(this.type == 'add'){
    			this.title = '新增商品'
    		}else{
    			this.getInfo()
    			this.title = '修改商品'
    		}
			uni.setNavigationBarTitle({
				title: this.title
			});
    		this.getDataList()
    		this.getClassList()	
    	},
    	getInfo() {
    	  goodsDetail({goodsId:this.goodsId}).then((res)=>{
			  for(let key in defaultForm){
				  this.form[key] = res[key] ? res[key] : defaultForm[key]
			  }
			    this.form.properties = [];
				this.form.report = [];
				this.form.goodsImages = []
			    res.featureList.properties.forEach((item)=>{
				  this.form.properties.push({url:item})
				})
				res.featureList.report.forEach((item)=>{
				  this.form.report.push({url:item})
				})
				res.goodsImages.forEach((item)=>{
				  this.form.goodsImages.push({url:item})
				})
				this.form.goodsPrice = res.goodsPrice+''
			  this.form.categoryName = res.parentCategoryName+'/'+res.categoryName
		  })
		  
    	},
		
    
    	getDataList() {
    	  getAreaList().then((res) => {
    	    this.dataTree = res;
    	  })
    	},
    	onpopupopened() {
    	  console.log('popupopened');
		  
    	},
    	onpopupclosed() {
    	  console.log('popupclosed');
    	},
    	onchange(e) {
    	  let ids = [];
    	  let txts = [];
    	  e.detail.value.forEach((item) => {
    	   txts.push(item.text)
    	   ids.push(item.value)
    	  });
    	  this.form.sendAreaId = ids[2] ? ids[2] : '' 
    	  this.form.sendArea = txts.join(" ")
    	},
    	saveForm(){
    		this.$refs.form.validate().then(res => {	
    		   this.btnLoading = true;
    		   let data = JSON.parse(JSON.stringify(this.form))
				 data.featureList = {};
				 data.featureList.properties = this.form.properties.map((item)=>item.url)
				 data.featureList.report = this.form.report.map((item)=>item.url)
				 data.goodsImages = this.form.goodsImages.map((item)=>item.url)
    			 setGoods({data:[data]}).then((res)=>{
    				   this.btnLoading = false;
    				   uni.showToast({
    				     title: '提交成功！',
    				     icon: 'none',
    				     duration: 2000,
    				   });
					   uni.navigateBack();	   	
    			 }).catch(()=>{
    				   this.btnLoading = false;
    			 })
    		}).catch(errors => {
    			
    		})
    		
    	},
      
   }
}
</script>

<style lang="scss" scoped>
  @import '@/style/common.scss';

  .dialog-quotation {
	padding-bottom:200rpx;

    .dialog-title {
      padding: 20rpx 10rpx;
      margin-bottom: 2px;
      font-size: $m-font;
      border-bottom: 0.8px solid $border-color;
      background-color: rgba(242, 242, 242, 1);
    }

  }
  .change-button {
    width: 100%;
    position: fixed;
    background-color: #fff;
    padding: 20rpx;
    bottom: 0;
    display: inline-block;
	z-index: 1;
  }

  .form-row {
    @include flexbox(flex-end, center);
  }
</style>